<script>
import { ethers } from 'ethers'
import { mapState } from 'vuex'
import Web3 from 'web3'

export default {
  mounted() {
    this.initEth()
  },

  methods: {
    // get current account
    async getCurrentAccount() {
      const res = await this.web3.eth
        .getAccounts()
        .then(res => {
          return res && res.length > 0 ? res[0] : null
        })
        .catch(error => {
          console.log(error)
        })
      this.$store.commit('changeEthAddress', res)
      this.$store.commit('ethpublickey', null)
    },

    checkAccountChanged(accounts) {
      if (accounts.length === 0) {
        this.$store.commit('changeEthAddress', null)
        this.$store.commit('ethpublickey', null)
      } else if (accounts[0] !== this.ethAddress) {
        this.$store.commit('changeEthAddress', accounts[0])
        this.$store.commit('ethpublickey', null)
      }
    },

    addEventListener(provider) {
      provider.on('accountsChanged', accounts => {
        this.checkAccountChanged(accounts)
      })
      provider.on('networkChanged', async network => {
        let web3Provider = window.ethereum || window.web3.currentProvider
        let web3 = new Web3(web3Provider)
        let ethersprovider = new ethers.providers.Web3Provider(web3Provider)
        this.$store.commit('changeweb3', { web3, ethersprovider })
        this.$store.commit('changeEthChainID', network)
        await this.getCurrentAccount()
      })
      provider.on('disconnect', () => {
        console.log('disconnect')
        this.checkAccountChanged([])
      })
    },

    // eth init
    async initEth() {
      //check if metamask is installed
      if (!window.ethereum && !window.web3) {
        this.$store.commit('changeEthAddress', null)
        this.$store.commit('changeEthChainID', null)
        return
      }

      let web3Provider = window.ethereum || window.web3.currentProvider
      let web3 = new Web3(web3Provider)
      let ethersprovider = new ethers.providers.Web3Provider(web3Provider)
      this.$store.commit('changeweb3', { web3, ethersprovider })

      const res = await this.web3.eth.getChainId().catch(err => {})
      this.$store.commit('changeEthChainID', res)

      this.addEventListener(web3Provider)

      var isConnect = await this.web3.eth
        .getCoinbase()
        .then(res => {
          return res ? true : false
        })
        .catch(err => {
          return false
        })

      if (!isConnect) return

      await this.getCurrentAccount()
    },
  },
  computed: {
    ...mapState([
      'ethAddress',
      'web3',
      'ethersprovider',
      'ethChainID',
      'walletConnectProvider',
      'walletName',
      'GlobalConfig',
    ]),
  },
}
</script>
